﻿//*** Guidance generated code ***//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http.ValueProviders;

using Newtonsoft.Json.Linq;

using ProjectBase.Core;
using ProjectBase.Mvc.Controllers;

namespace $safeprojectname$
{
    /// <summary>
    ///     Extensions available on every place of the framework.
    /// </summary>
    public static partial class Ext
    {
        public static object TryGetValue(this JProperty property, Type type)
        {
            string name = property.Name;
            JToken jValue = property.Value;
            
            object value = null;

            try
            {
                if (type.HasType<string>())
                {
                    value = jValue.Value<string>();
                }
                else if (type.HasType<int>())
                {
                    value = jValue.Value<int>();
                }
                else if (type.HasType<long>())
                {
                    value = jValue.Value<long>();
                }

                else if (type.HasType<short>())
                {
                    value = jValue.Value<short>();
                }

                else if (type.HasType<float>())
                {
                    value = jValue.Value<float>();
                }

                else if (type.HasType<DateTime>())
                {
                    value = jValue.Value<DateTime>();
                }
                else if (type.HasType<bool>())
                {
                    value = jValue.Value<bool>();
                }
                else if (type.HasType<uint>())
                {
                    value = jValue.Value<uint>();
                }
                else if (type.HasType<short>())
                {
                    value = jValue.Value<short>();
                }
                else if (type.HasType<decimal>())
                {
                    value = jValue.Value<decimal>();
                }
                else if (type.HasType<Guid>())
                {
                    value = jValue.Value<Guid>();
                }
                else
                {
                    PublishingManager.Publish(null, Severity.Error, "Not supported Value/ID type {0}. Cannot bind from JSON", type.Name);
                }
            }
            catch (Exception ex)
            {
                PublishingManager.Publish(null, "Cannot get Value/ID for [{0}] (from: {1})".FormatWith(name, value), ex);
            }

            return value;
        }

        public static TID TryGetValue<TID>(this JProperty property)
        {
            var type = typeof(TID);

            return (TID)TryGetValue(property, type);
        }
    }
}